//
//  WYNetWorkingTools.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/10.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

import AFNetworking


enum Requesttype: Int {

    case GET
    case POST
}
//创建一个网络工具类 继承自 AFHTTPSessionManager
class WYNetWorkingTools: AFHTTPSessionManager {
    //闭包回调别名
    typealias CallBack = (response: AnyObject?, error: NSError?)->()
    
    //全局单例访问点
    static let sharedTools: WYNetWorkingTools = {
        let tools = WYNetWorkingTools()
        //增加一种 返回数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    //疯装图片上传
    func requestUpload(url: String, params: AnyObject?, imageData: NSData, name: String, callBack: CallBack) {
    
        //上传图片接口
        /*!
        *           imageData: 上传图片所需要二进制数据
                    name: 服务器的获取数据参数
                    fileName: 告诉服务器我们的文件名字,服务器一般不会用,他们会自动生成唯一的一个图片名
                    timeType: 资源类型,octet-stream 通用的资源类型
       
        */
        POST(url, parameters: params, constructingBodyWithBlock: { (fromData) -> Void in
            fromData.appendPartWithFileData(imageData, name: name, fileName: "test", mimeType: "octet-stream")
            }, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
            }) { (_, error) -> Void in
                callBack(response: nil, error: error)
        }
        
    }
    
    //封装 请求 
    func request(type: Requesttype, url: String, param: AnyObject?, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        if type == .GET {
        
             GET(url, parameters: param, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                
                }, failure: { (_, error) -> Void in
                callBack(response: nil, error: error)
             })
        } else {
        
             POST(url, parameters: param, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                 callBack(response: nil, error: error)
             })
       
        }
       
    }
}

//OAuth 相关接口

extension WYNetWorkingTools {

    func requestAccesstoken(code: String ,callBack:(response: AnyObject?, error: NSError?) -> ()){
        
        //获取网址https://api.weibo.com/oauth2/access_token
        let url = "https://api.weibo.com/oauth2/access_token"
        //返回值 参数
        let prams = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Uri
        ]
        
        //接口请求 获取用户信息
        request(.POST, url: url, param: prams, callBack: callBack)
        
    }
    
    //获取用户信息
    func requestUserInfos(userAccount: WYUserAccount, callBack: (response: AnyObject?, error: NSError?) -> ()){
    
        let url = "https://api.weibo.com/2/users/show.json"
        
        //int64 跟字符串放在一起编译不通过 需要转化为字符串
        let params = [
            
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        
//        let urlStr = url + "?access_token=\(userAccount.access_token!)&uid=\(userAccount.uid)"
        request(.GET, url: url, param: params, callBack: callBack)
    }
    
    
}

//MARK -- 首页微博相关接口

extension WYNetWorkingTools {
    
    func loadStatus(maxID: Int64 = 0, sinceID: Int64 = 0 , callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        
        //准备接口位置
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        //参数
        let prarms = [
        
            "access_token": WYUserAccountViewModel.sharedUserAccount.accessToken!,
            "since_id": "\(sinceID)",
            "max_id": "\(maxID)"
            
        ]
        
        print(url + "?access_token=" + WYUserAccountViewModel.sharedUserAccount.accessToken!)
       //发送请求
        request(.GET, url: url, param: prarms, callBack: callBack)
    }
    
    
    
}
//发送文字微博接口

extension WYNetWorkingTools {
    
    func update(access_token: String, status: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
    
        //准备接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //参数
        let param = [
            "access_token": access_token,
            "status": status
            
            ]
        //使用公有函数进行网络请求
        request(.POST, url: url, param: param, callBack: callBack)
    }
    
}

//MARK: -- 发送图片微博
extension WYNetWorkingTools {

    func upload(access_token: String, status: String,image: UIImage, callBack: (response: AnyObject?, error: NSError?)-> ()) {
        //准备 url 地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let parma = [
        
            "access_token": access_token,
            "status": status
        ]
//        let imageData = UIImagePNGRepresentation(image)
//        imageData?.writeToFile("/User/wangyi/Desktop/1.png", atomically: true)
        //compressionQuality 质量系数 0-1 系数越小质量越低
        let imageData = UIImageJPEGRepresentation(image, 0.5)
//        POST(url, parameters: parma, constructingBodyWithBlock: { (formData) -> Void in
//            formData.appendPartWithFileData(imageData!, name: "pic", fileName: "test", mimeType: "image/jpeg")
//            }, progress: nil, success: { (_, response) -> Void in
//                callBack(response: response, error: nil)
//            }) { (_, error) -> Void in
//                callBack(response: nil, error: error)
//        }
        requestUpload(url, params: parma, imageData: imageData!, name: "pic", callBack: callBack)
    }
}



